package weaver.formmode.customjavacode;

import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.soa.workflow.request.RequestInfo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 导入宿舍费用后
 * 计算每个人入住天数及每月费用
 *
 * @author Lee
 */
public class CalculateDormitoryCostExpand extends AbstractModeExpandJavaCodeNew {
    private static String formModeId = "32";
    private static String formCusId = "39";

    @Override
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        BaseBean bb = new BaseBean();
        Map<String, String> result = new HashMap<String, String>();
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs2 = new RecordSet();
            int billid = -1;
            int modeid = -1;
            //查询所有未核算的主表id
            String sql = "select a.id,a.dyxzzq,a.dysdf from uf_jycsssdfwh a where a.sfhs is null or a.sfhs=1";
            RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo");
            if (requestInfo != null) {
                billid = Util.getIntValue(requestInfo.getRequestid());
                modeid = Util.getIntValue(requestInfo.getWorkflowid());
                if (billid > 0 && modeid > 0) {
                    sql = "select a.id,a.dyxzzq,a.dysdf from uf_jycsssdfwh a where a.id=" + billid;
                }
            }
            //查询需要参与水电扣费的人员
            String detailSql = "select c.id,c.xm,c.rzsj,c.tssj  from uf_jycsssdfwh a " +
                    "left join uf_ssxxwh b on b.ssbh=a.ssbh " +
                    "left join uf_ssxxwh_dt1 c on c.mainid=b.id " +
                    "where a.id = ? and c.rzsj is not null and c.rzsj !='' and c.rzsj<=? and " +
                    "(c.tssj is null or c.tssj ='' or c.tssj<=?)";
            String insertSq = "insert into uf_jycsssdfwh_dt1 (mainid,xm,rzsj,tssj,xzzqnzsts,dysdft) values(?,?,?,?,?,?)";
            rs.executeQuery(sql);
            while (rs.next()) {
                String id = rs.getString("id");
                String month = rs.getString("dyxzzq");
                String totalCost = rs.getString("dysdf");
                String monthStart = getStartDate(month);
                String monthEnd = getEndDate(month);
                int countDay = 0;
                //该宿舍下每月水电核算明细的集合
                List<List> lists = new ArrayList<>();
                //先删除
                rs2.executeUpdate("delete from uf_jycsssdfwh_dt1 where mainid=?", id);
                rs2.executeQuery(detailSql, id, monthEnd, monthEnd);
                while (rs2.next()) {
                    List<Object> list = new ArrayList<>();
                    lists.add(list);
                    String xm = rs2.getString("xm");
                    String rzsj = rs2.getString("rzsj");
                    String tssj = rs2.getString("tssj");
                    list.add(id);
                    list.add(xm);
                    list.add(rzsj);
                    list.add(tssj);
                    //计算住了多少天
                    //当月之前就入住
                    if (rzsj.compareTo(monthStart) <= 0) {
                        //当月走了
                        if (StringUtils.isNotEmpty(tssj) && tssj.compareTo(monthEnd) <= 0) {
                            int count = calculateDays(monthStart, tssj);
                            list.add(count);
                            countDay += count;
                        } else {
                            //当月没走
                            int count = calculateDays(monthStart, monthEnd);
                            list.add(count);
                            countDay += count;
                        }
                    } else {
                        //当月才入住的
                        //当月走了
                        if (StringUtils.isNotEmpty(tssj) && tssj.compareTo(monthEnd) <= 0) {
                            int count = calculateDays(rzsj, tssj);
                            list.add(count);
                            countDay += count;
                        } else {
                            //当月没走
                            int count = calculateDays(rzsj, monthEnd);
                            list.add(count);
                            countDay += count;
                        }
                    }
                }

                //计算每天电费
                double unitPrice = calculateCost(totalCost, countDay);
                for (List list : lists) {
                    //第4个元素是住了多少天
                    int count = (int) list.get(4);
                    BigDecimal total = new BigDecimal(unitPrice * count).setScale(2, RoundingMode.HALF_UP);
                    list.add(total);
                }
                bb.writeLog("insertSq-lists" + lists);
                //插入水电费明细
                boolean flag = rs2.executeBatchSql(insertSq, lists);
                if (flag) {
                    rs2.executeUpdate("update uf_jycsssdfwh set sfhs=0 where id=?", id);
                }
            }
            //权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(1, Integer.parseInt(formModeId), Integer.parseInt(formCusId));
        } catch (Exception e) {
            bb.writeLog("CalculateDormitoryCostExpand-e-" + e.getMessage());
        }
        return result;
    }

    private static double calculateCost(String totalCost, int countDay) {
        if (countDay == 0) {
            return 0;
        }
        // 定义被除数和除数
        String toString = Double.toString(Double.parseDouble(totalCost) / countDay);
        return new BigDecimal(toString).doubleValue();

    }

    private static String getStartDate(String month) {
        // 解析输入为YearMonth对象
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取该月份的第一天
        LocalDate startOfMonth = yearMonth.atDay(1);
        return startOfMonth.toString();
    }

    private static String getEndDate(String month) {
        // 解析输入为YearMonth对象
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取该月份的第一天
        LocalDate endOfMonth = yearMonth.atEndOfMonth();
        return endOfMonth.toString();
    }


    private static int calculateDays(String dateStr, String dateStr2) {
        // 解析输入的日期
        LocalDate date = LocalDate.parse(dateStr);
        LocalDate date2 = LocalDate.parse(dateStr2);
        // 计算两个日期之间的天数差，包括当天
        long daysUntilEndOfMonth = ChronoUnit.DAYS.between(date, date2) + 1;
        return daysUntilEndOfMonth > 0 ? (int) daysUntilEndOfMonth : 0;
    }
}